'use strict';
const dayjs = require("dayjs");

module.exports = app => {
    const { INTEGER, DATE, STRING, TEXT } = app.Sequelize;
    const HouseFollowup = app.model.define(
        'HouseFollowup',
        {
            id: { type: INTEGER, primaryKey: true, autoIncrement: true },
            // 关联的写字楼ID
            office_building_id: INTEGER,
            // 员工ID
            employee_id: INTEGER,
            // 员工姓名
            employee_name: STRING(50),
            // 跟进备注
            remark: TEXT,
            // 跟进图片，存储JSON数组格式的图片URL
            images: {
                type: TEXT,
                get() {
                    const rawValue = this.getDataValue('images');
                    // 判断是否为json数组字符串
                    if (typeof rawValue === 'string' && rawValue.startsWith('[') && rawValue.endsWith(']')) {
                        return  JSON.parse(rawValue)
                    }
                    return [];
                },
                set(value) {
                    this.setDataValue('images', Array.isArray(value) ? JSON.stringify(value) : '[]');
                }
            },
            // 创建时间
            create_time: {
                type: DATE,
                get() {
                    return this.getDataValue('create_time') ? dayjs(this.getDataValue('create_time')).format('YYYY-MM-DD HH:mm:ss') : null;
                }
            },
            // 更新时间
            updated_time: {
                type: DATE,
                get() {
                    return this.getDataValue('updated_time') ? dayjs(this.getDataValue('updated_time')).format('YYYY-MM-DD HH:mm:ss') : null;
                }
            }
        },
        {
            tableName: 'house_followup',
            timestamps: true,
            createdAt: 'create_time',
            updatedAt: 'updated_time'
        }
    );

    HouseFollowup.associate = function() {
        // 关联写字楼表
        app.model.HouseFollowup.belongsTo(app.model.OfficeBuilding, {
            foreignKey: 'office_building_id',
            as: 'officeBuilding'
        });
    };

    return HouseFollowup;
};
